package com.xpengplayer.update;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.xpengplayer.R;

import java.io.File;
import java.text.DecimalFormat;

/**
 * 更新通知对话框
 * 用于显示更新信息并提供更新操作选项
 */
public class UpdateDialog {
    private Context context;
    private UpdateInfo updateInfo;
    private AlertDialog dialog;
    private UpdateManager updateManager;
    private TextView progressText;
    private ProgressBar progressBar;
    private boolean isDownloading = false;
    private String currentVersionName;
    private int currentVersionCode;
    
    public interface OnUpdateListener {
        void onUpdate();
        void onCancel();
        void onRetry();
    }
    
    /**
     * 检查对话框是否正在显示
     */
    public boolean isShowing() {
        return dialog != null && dialog.isShowing();
    }
    
    private OnUpdateListener onUpdateListener;
    
    public UpdateDialog(Context context, UpdateInfo updateInfo) {
        this.context = context;
        this.updateInfo = updateInfo;
        this.updateManager = UpdateManager.getInstance(context);
        // 获取当前版本信息
        try {
            this.currentVersionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
            this.currentVersionCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (Exception e) {
            this.currentVersionName = "未知";
            this.currentVersionCode = 0;
        }
    }
    
    // 接受UpdateManager的构造器，用于外部传入已有实例
    public UpdateDialog(Context context, UpdateInfo updateInfo, UpdateManager updateManager) {
        this.context = context;
        this.updateInfo = updateInfo;
        this.updateManager = updateManager;
        // 获取当前版本信息
        try {
            this.currentVersionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
            this.currentVersionCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (Exception e) {
            this.currentVersionName = "未知";
            this.currentVersionCode = 0;
        }
    }
    
    public void setOnUpdateListener(OnUpdateListener listener) {
        this.onUpdateListener = listener;
    }
    
    /**
     * 显示更新对话框
     */
    public void show() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        // 使用更详细的标题，包含新旧版本信息
        builder.setTitle("发现新版本: " + updateInfo.getVersionName());
        
        // 使用自定义布局以更好地显示版本信息
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_update_info, null);
        TextView tvCurrentVersion = view.findViewById(R.id.tv_current_version);
        TextView tvNewVersion = view.findViewById(R.id.tv_new_version);
        TextView tvUpdateContent = view.findViewById(R.id.tv_update_content);
        TextView tvFileSize = view.findViewById(R.id.tv_file_size);
        
        if (tvCurrentVersion != null) {
            tvCurrentVersion.setText("当前版本: v" + currentVersionName + " (" + currentVersionCode + ")");
        }
        
        if (tvNewVersion != null) {
            tvNewVersion.setText("新版本: v" + updateInfo.getVersionName() + " (" + updateInfo.getVersionCode() + ")");
        }
        
        // 格式化更新日志显示
        String updateContent = updateInfo.getUpdateLog();
        if (tvUpdateContent != null) {
            if (!TextUtils.isEmpty(updateContent)) {
                Spanned updateLog = Html.fromHtml(updateContent);
                tvUpdateContent.setText(updateLog);
            } else {
                tvUpdateContent.setText("更新内容: 优化用户体验，修复已知问题");
            }
        }
        
        // 添加文件大小信息
        if (tvFileSize != null) {
            tvFileSize.setText("文件大小: " + formatFileSize(updateInfo.getFileSize()));
        }
        
        builder.setView(view);
        
        // 设置按钮
        if (updateInfo.isForceUpdate()) {
            // 强制更新，只提供立即更新按钮
            builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    startDownload();
                    if (onUpdateListener != null) {
                        onUpdateListener.onUpdate();
                    }
                }
            });
            
            // 强制更新不允许取消
            builder.setCancelable(false);
        } else {
            // 可选更新，提供立即更新和稍后提醒按钮
            builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    startDownload();
                    if (onUpdateListener != null) {
                        onUpdateListener.onUpdate();
                    }
                }
            });
            
            builder.setNegativeButton("稍后提醒", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (onUpdateListener != null) {
                        onUpdateListener.onCancel();
                    }
                    dialog.dismiss();
                }
            });
        }
        
        dialog = builder.create();
        dialog.show();
    }
    
    /**
     * 开始下载更新
     */
    private void startDownload() {
        isDownloading = true;
        
        // 显示下载进度对话框
        showDownloadProgressDialog();
        
        // 开始下载APK
        updateManager.downloadApk(updateInfo.getApkUrl());
        
        // 注意：由于DownloadManager在后台运行，实际的下载完成通知由系统处理
        // 这里只是模拟进度，真实场景需要监听DownloadManager的下载状态
    }
    
    /**
     * 显示下载进度对话框
     */
    private void showDownloadProgressDialog() {
        // 如果已有对话框，先关闭
        dismiss();
        
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("正在下载更新");
        
        // 自定义布局
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_download_progress, null);
        progressBar = view.findViewById(R.id.progress_bar);
        progressText = view.findViewById(R.id.progress_text);
        
        builder.setView(view);
        
        if (updateInfo.isForceUpdate()) {
            builder.setCancelable(false); // 强制更新下载过程中不允许取消
            builder.setPositiveButton("下载中...", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // 强制更新下载中不执行任何操作
                }
            });
        } else {
            builder.setPositiveButton("下载中...", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // 下载中不执行任何操作
                }
            });
            
            builder.setNegativeButton("取消下载", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    updateManager.cancelDownload();
                    isDownloading = false;
                    dialog.dismiss();
                }
            });
        }
        
        dialog = builder.create();
        dialog.show();
        
        // 禁用下载中按钮
        Button positiveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
        if (positiveButton != null) {
            positiveButton.setEnabled(false);
        }
    }
    
    /**
     * 设置下载进度
     */
    public void setProgress(int progress, long downloadedSize, long totalSize) {
        if (progressBar != null) {
            progressBar.setProgress(progress);
        }
        if (progressText != null) {
            progressText.setText(formatFileSize(downloadedSize) + " / " + formatFileSize(totalSize) + " (" + progress + "%)");
        }
    }
    
    /**
     * 下载完成
     */
    public void downloadComplete() {
        isDownloading = false;
        if (dialog != null && dialog.isShowing() && dialog.getButton(DialogInterface.BUTTON_POSITIVE) != null) {
            Button positiveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
            positiveButton.setText("立即安装");
            positiveButton.setEnabled(true);
            
            positiveButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    updateManager.installApk();
                    dialog.dismiss();
                }
            });
        }
    }
    
    /**
     * 下载失败
     */
    public void downloadFailed(String errorMessage) {
        isDownloading = false;
        if (dialog != null && dialog.isShowing()) {
            Button positiveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
            if (positiveButton != null) {
                positiveButton.setText("重试");
                positiveButton.setEnabled(true);
                
                positiveButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startDownload();
                        if (onUpdateListener != null) {
                            onUpdateListener.onRetry();
                        }
                    }
                });
            }
            
            if (!updateInfo.isForceUpdate()) {
                Button negativeButton = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
                if (negativeButton != null) {
                    negativeButton.setText("取消");
                }
            }
        }
        
        // 显示错误信息
        Toast.makeText(context, "下载失败: " + errorMessage, Toast.LENGTH_SHORT).show();
    }
    
    /**
     * 格式化文件大小显示
     */
    private String formatFileSize(long bytes) {
        if (bytes < 1024) {
            return bytes + " B";
        } else if (bytes < 1024 * 1024) {
            return new DecimalFormat("#.##").format(bytes / 1024.0) + " KB";
        } else if (bytes < 1024 * 1024 * 1024) {
            return new DecimalFormat("#.##").format(bytes / (1024.0 * 1024)) + " MB";
        } else {
            return new DecimalFormat("#.##").format(bytes / (1024.0 * 1024 * 1024)) + " GB";
        }
    }
    
    /**
     * 关闭对话框
     */
    public void dismiss() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}